/*
* @Author: admin
* @Date:   2018-07-17 10:00:30
* @Last Modified by:   Administrator
* @Last Modified time: 2018-07-19 00:35:39
*/
const express = require('express');
const app = express();
const MongoClient = require('mongodb').MongoClient;
const fs = require('fs');
const url2 = require('url');
const path = require('path');
const db = require('./db.js')
const querystring = require('querystring');
const myjson = JSON.parse(fs.readFileSync('static/record.json','utf8')).myrecord;
var url = "mongodb://127.0.0.1:27017";
var t = 0;
var num = 0;
// 设置一页多少条数据
var pageSize = 10;

// 一开始加载./static文件夹下的index.html
app.use(express.static('./static'));

// 加载所有数据
app.get('/all',function(req,res){
	res.writeHead(200,{"Content-Type":"test/html;charset = utf8"});
	MongoClient.connect(url,function(err,db){
		if(err) throw err;
		console.log('数据库连接成功')
		// 数据库名字
		var dbase = db.db('record');
		// 数据库集合
		dbase.collection('myrecord').find().limit(pageSize).toArray(function(err,result){
			var re ={
				"page":{
					"currentPage":1,//当前页
					"pageSize":pageSize,//一页多少条数据
					"dataCount":dbase.collection('myrecord').count()//数据总量
				},
				"result":result//结集
			};
			res.end(JSON.stringify(re));
		})	
		db.close()
	})

});

// 分页
app.get('/getPage',function(req,res){ 
	res.writeHead(200,{"Content-Type":"test/html;charset = utf8"});  
	// 上一页
	if(parseInt(querystring.parse(url2.parse(req.url).query).page) == -1){
		if(num == 0){
			num =0;
		}else{
			num = --t;
		}	
		// 下一页
	}else if(parseInt(querystring.parse(url2.parse(req.url).query).page) == -2){
		if(num == 5){
			num = 5
		}else{
			num = ++t;
		}
		
	}else{
		num = parseInt(querystring.parse(url2.parse(req.url).query).page)-1;
	}	
	MongoClient.connect(url,function(err,db){
		if(err) throw err;
		console.log('数据库连接成功')
		var dbase = db.db('record');
		dbase.collection('myrecord').find().limit(pageSize).skip(pageSize*num).toArray(function(err,result){
			var re ={
				"page":{
					"currentPage":parseInt(num+1),//当前页
					"pageSize":pageSize,//一页多少条数据
					"dataCount":dbase.collection('myrecord').count()//数据总量
				},
				"result":result//结集
			};
			console.log(dbase.collection('myrecord').count());
			res.end(JSON.stringify(re));
		})	
		db.close()
	})
	// 记录上一页的num
	t = num; 

})

app.listen(8989);

